package com.wanqh.reptitle.service.zhihu;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.wanqh.reptitle.service.SearchService;
import com.wanqh.reptitle.utils.ExcelUtil;
import com.wanqh.reptitle.utils.SpiderUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service(value = "zhiHuSearchService")
@Slf4j
public class ZhiHuSearchServiceImpl implements SearchService {

    private static String ZHI_HU_TOPIC_SEARCH_URL = "https://www.zhihu.com/search?type=topic&q=";

    @Autowired
    @Qualifier("firefoxWebDriver")
    private WebDriver firefoxWebDriver;

    @Override
    public String getPlatform() {
        return "知乎";
    }

    @Override
    public void initExcel() throws Exception {
        ExcelUtil.initExcel(getPlatform(), new String[]{"文件品牌","搜索匹配结果",	"链接"}, SpiderUtils.FILE_PATH);
    }

    @Override
    public String[][] ServiceBrand(@NonNull String brand) {
        if(StrUtil.isEmpty(brand)) {
            return null;
        }
        String[][] result = new String[][]{{brand}};
        try {
            firefoxWebDriver.get(ZHI_HU_TOPIC_SEARCH_URL + brand);
            // 等待页面加载完成
            ThreadUtil.sleep(RandomUtil.randomInt(1, 5), TimeUnit.SECONDS);
            Document parse = Jsoup.parse(firefoxWebDriver.getPageSource());
            Element searchMainEle = parse.getElementById("SearchMain");
            if(searchMainEle != null) {
                Element attr = searchMainEle.attr("data-za-detail-view-path-index", "0");
                if(attr != null) {
                    Elements h2Eles = attr.getElementsByTag("h2");
                    if(CollUtil.isNotEmpty(h2Eles)) {
                        Element headEle = h2Eles.get(0);
                        Element topicLink = headEle.getElementsByClass("TopicLink").get(0);
                        String href = "https:" + topicLink.attr("href");
                        String text = topicLink.getElementsByClass("Highlight").get(0).text();
//                        searchResult.setSearchText(text);
//                        searchResult.setUrl(href);
                        if(SpiderUtils.isContains(text, brand)){
                            result[0] = new String[]{brand, text, href};
                        }
//                        log.info("知乎:[{}],地址:[{}]", text, href);
                    }
                }
            }
        } catch (Exception e) {
            log.error("抓取知乎异常！",e);
            result[0][1] = "异常";
        }

        return result;
    }


}
